<template>
  <div class="container">
    <el-row class="section">
      <el-col :span="8" class="section-title">资讯量分析</el-col>
      <el-col :span="16" class="section-toolbar">
        <date-range-picker
          v-model="datePicker1"
          type="daterange"
          align="right"
          size="small"
          class="w-240"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="timeChange"/>
        <el-select v-model="listQuery.lan" size="small" class="w-150">
          <el-option :value="null" label="全部资讯语言"/>
          <el-option v-for="(item,key) in lan" :key="key" :label="key" :value="item"/>
        </el-select>
        <el-select v-model="listQuery.source" size="small" class="w-150">
          <el-option :value="null" label="全部频道入口"/>
          <el-option v-for="(item,key) in newsSourceOpt" :key="key" :label="key" :value="item"/>
        </el-select>
        <el-button type="primary" icon="el-icon-search" size="small" @click="search()">搜索</el-button>
      </el-col>
    </el-row>

    <el-row class="p-t-15">
      <el-col>
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="资讯阅读量uv" name="first">
            <el-card class="box-card">
              <div class="title">
                <p> 资讯阅读量uv排行（条）</p>
                <div class="btn">
                  <el-button class="fr m-l-10" size="small" @click="toExport('add')">导出
                  </el-button>
                </div>
              </div>
              <div class="echart">
                <div id="add" :style="{width: '1600px', height: '380px'}"/>
              </div>
            </el-card>
          </el-tab-pane>
          <el-tab-pane label="资讯阅读量pv" name="second">
            <el-card class="box-card">
              <div class="title">
                <p> 资讯阅读量pv排行（条）</p>
                <div class="btn">
                  <el-button class="fr m-l-10" size="small" @click="toExport('pass')">导出
                  </el-button>
                </div>
              </div>
              <div class="echart">
                <div id="pass" :style="{width: '1600px', height: '380px'}"/>
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import echarts from 'echarts';
import { dateShortcutKeyJS } from '@/mixins/index.js';
import timeUtils from '@/utils/timeHandle.js';
import { exportJsonToExcel, formatJson } from '@/utils/excel/Export2Excel';
import {
  readPv,
  readUv
} from '@/api/information-content-analysis.js';
import '@/assets/css/common/style.scss';
const HeadWithOutWeek = {
  add: [
    {
      prop: 'date',
      label: '日期'
    },
    {
      prop: 'channelName',
      label: '频道'
    },
    {
      prop: 'total',
      label: '阅读量uv'
    }
  ],
  pass: [
    {
      prop: 'date',
      label: '日期'
    },
    {
      prop: 'channelName',
      label: '频道'
    },
    {
      prop: 'total',
      label: '阅读量pv'
    }
  ]
};
export default {
  mixins: [dateShortcutKeyJS],
  data() {
    return {
      tableName: {
        add: '资讯阅读量uv',
        pass: '资讯阅读量pv'
      },
      tableHead: HeadWithOutWeek,
      activeName: 'first',
      lan: {
        中文: 'zh-Hans',
        柬文: 'km-KH'
      },
      newsSourceOpt: {
        资讯入口: 7,
        视频入口: 8
      },
      datePicker1: [
        timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 6,
          'date'
        ),
        timeUtils.timeHandle(new Date().getTime(), 'date')
      ],
      listQuery: {
        lan: null,
        source: null,
        beginDate: timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 6,
          'date'
        ),
        endDate: timeUtils.timeHandle(new Date().getTime(), 'date'),
        time: 'day' // day, week, month
      },
      xData1: [], // 保存活跃用户实时分布x轴数据
      xData2: [], // 保存活跃阅读资讯人数x轴数据
      legend: {
        1: ['柬文', '中文'],
        2: ['柬文', '中文']
      },
      list: {
        uv: [],
        pv: []
      },
      exportData: {
        // 导出表格数据
        add: [], // 新增资讯柬文
        pass: [] // 审核通过柬文
      },
      isFirstRender: true
    };
  },
  mounted() {
    this.search();
  },
  methods: {
    timeChange(time) {
      if (!time) return;
      const startTime = Date.parse(time[0]);
      const endTime = Date.parse(time[1]);
      const Days = Math.floor(Math.abs(endTime - startTime) / (24 * 3600 * 1000));
      if (Days <= 30) {
        this.listQuery.time = 'day';
      } else if (Days > 30 && Days <= 42) {
        this.listQuery.time = 'week';
      } else if (Days > 42) {
        this.listQuery.time = 'month';
      }
    },

    getData1() {
      var myChart = echarts.init(document.getElementById('add'));
      myChart.showLoading();

      readUv(this.listQuery).then(res => {
        if (res.code == 200) {
          const data = res.data || [];

          this.xData1 = [];
          this.list.uv = [];

          this.exportData.add = data;
          for (var i = 0; i < data.length; i++) {
            this.xData1.push(data[i].channelName);
            this.list.uv.push(data[i].total);
          }

          this.updateEchart1();
        }
      });
    },

    updateEchart1() {
      var myChart = echarts.init(document.getElementById('add'));
      myChart.showLoading();

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: this.legend[1],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [
          {
            type: 'category',
            data: this.xData1,
            axisLabel: {
              // 坐标轴刻度标签的相关设置。
              interval: 0,
              rotate: this.xData1.length > 5 ? '-20' : '0'
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            type: 'bar',
            itemStyle: {
              normal: {
                color: 'rgba(97, 165, 232, 1)'
              }
            },
            data: this.list['uv']
          }
        ]
      };

      myChart.setOption(option, true);
      myChart.hideLoading();
    },

    getData2() {
      if (!this.isFirstRender) {
        var myChart = echarts.init(document.getElementById('pass'));
        myChart.showLoading();
      }
      readPv(this.listQuery).then(res => {
        if (res.code == 200) {
          const data = res.data || [];

          this.xData2 = [];
          this.list.pv = [];

          this.exportData.pass = data;
          for (var i = 0; i < data.length; i++) {
            this.xData2.push(data[i].channelName);
            this.list.pv.push(data[i].total);
            // this.list.passKm.push(data[i].km)
            // this.list.passZh.push(data[i].zh)
          }

          this.$nextTick(function() {
            this.updateEchart2();
          });
        }
      });
    },

    updateEchart2() {
      var myChart = echarts.init(document.getElementById('pass'));
      myChart.showLoading();

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: this.legend[1],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [
          {
            type: 'category',
            data: this.xData2,
            axisLabel: {
              // 坐标轴刻度标签的相关设置。
              interval: 0,
              rotate: this.xData2.length > 5 ? '-20' : '0'
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            type: 'bar',
            itemStyle: {
              normal: {
                color: 'rgba(97, 165, 232, 1)'
              }
            },
            data: this.list['pv']
          }
        ]
      };

      myChart.setOption(option, true);
      myChart.hideLoading();
      this.isFirstRender = false;
    },

    search() {
      if (!this.datePicker1) {
        this.$message.warning('请输入搜索时间', true);
        return;
      }
      this.listQuery.beginDate = this.datePicker1[0];
      this.listQuery.endDate = this.datePicker1[1];

      this.getData1();
      this.getData2();
    },

    toExport(exportName) {
      const exprtTime = timeUtils.timeHandle(new Date().getTime(), 'date');
      const tHeader = this.tableHead[exportName].map(item => item.label);
      const tKey = this.tableHead[exportName].map(item => item.prop);
      const data = formatJson(tKey, this.exportData[exportName]); // 数据格式化
      const fileName = this.tableName[exportName] + exprtTime;
      exportJsonToExcel(tHeader, data, fileName); // 导出文件
    }
  }
};
</script>
<style lang="scss" scoped>
.w-150 {
  width: 150px;
}
.title {
  height: 32px;
  position: relative;
  p {
    font-size: 22px;
    line-height: 32px;
    text-align: center;
  }
  .btn {
    width: 400px;
    height: 32px;
    position: absolute;
    right: 0;
    top: 0;
  }
}
</style>
